package com.zhuang.LeetCodeHot100;

import java.util.*;

/**
 * @Classname Solution05
 * @Description LeetCode 热题 HOT
 * @Date 2025/7/14 12:57
 * @Author by Zhuang
 */

public class Solution05 {
    public static void main(String[] args) {

    }


    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pA = headA;
        while (pA != null) {
            pA.val = -pA.val;
            pA = pA.next;
        }
        ListNode res = null;
        ListNode pB = headB;
        while (pB != null) {
            if (pB.val < 0) {
                res = pB;
                break;
            }
            pB = pB.next;
        }
        pA = headA;
        while (pA != null) {
            pA.val = -pA.val;
            pA = pA.next;
        }
        return res;
    }

    public static ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }

    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ArrayList<Integer> list = new ArrayList<>();
        ListNode a = head;
        while (a != null) {
            list.add(a.val);
            a = a.next;
        }
        ListNode res = new ListNode();
        a = res;
        for (int i = list.size() - 1; i >= 0; i--) {
            a.next = new ListNode(list.get(i));
            a = a.next;
        }
        return res.next;
    }

    public ListNode detectCycle(ListNode head) {
        ListNode temp = head;
        HashSet<ListNode> set = new HashSet<>();
        while (temp != null) {
            if (set.contains(temp)) {
                return temp;
            } else {
                set.add(temp);
            }
            temp = temp.next;
        }
        return null;
    }
}
